import java.io.IOException;
import java.net.MalformedURLException;

import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import websphinx.Link;
import websphinx.Tag;


public class ExtendedLink {

	public enum TYPE{
		REGULAR, QUERY, FORM;
	}
	
	private TYPE linkType;
	private Query query;
	private Link link;
	
	
	public ExtendedLink(Link l) throws MalformedURLException {
		this.link = l;
		setLinkType();
		this.query = null;
		
	}
	
	private void setLinkType() throws MalformedURLException{
		//check if link is a query
		if (link.getQuery()!=""){
			linkType = ExtendedLink.TYPE.QUERY;
			Query query = new Query(link.toURL());
			setQueryParams(query);
			setQueryValues();
			//TODO: check if link is a form - need improvment
			if (link.getStartTag().getTagName().equals(Tag.INPUT)){
				linkType = ExtendedLink.TYPE.FORM;
				setQueryValues();
			}
		}
		else
			linkType = ExtendedLink.TYPE.REGULAR;
	}
	
	public boolean isLinkHTML() throws ParserException, IOException{
		Parser parser = new Parser(this.link.toURL());
		NodeList nl = parser.extractAllNodesThatMatch(new TagNameFilter("html"));
		if (nl.size()>0)
			return true;
		else
			return false;
	}

	public TYPE getLinkType() {
		return linkType;
	}

	public void setLinkType(TYPE linkType) {
		this.linkType = linkType;
	}

	public Query getQueryParams() {
		return query;
	}

	public void setQueryParams(Query query) {
		this.query = query;
	}
	
	public void setQueryValues(){
		this.query.setValues();
	}

	public Link getLink() {
		return link;
	}

	public void setLink(Link link) {
		this.link = link;
	}

}
